﻿using PmSoft;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;

namespace ManagementApi.Mvc.Authorization
{
    public class PermissionCheckPolicyHandler : AttributeAuthorizationHandler<PermissionCheckPolicyRequirement, PermissionCheckAttribute>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
            PermissionCheckPolicyRequirement requirement, IEnumerable<PermissionCheckAttribute> attributes)
        {
            bool passed = false;
            if (context.User.Identity.IsAuthenticated)
            {
                IAuthorizer? authorizer = null;
                if (context.Resource is DefaultHttpContext httpContext)
                {
                    authorizer = httpContext.RequestServices.GetService<IAuthorizer>();
                }

                if (authorizer == null)
                    throw new ArgumentNullException(nameof(authorizer));

                foreach (var permissionAttribute in attributes)
                {
                    if (authorizer.Authorize(permissionAttribute.PermissionKey))
                    {
                        passed = true;
                        break;
                    }
                }
            }
            if (passed)
                context.Succeed(requirement);
            else
                context.Fail();

            return Task.CompletedTask;
        }

    }
}
